<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .tab {
        width: 50%;
        height: 200px;
        margin: 10px auto;
        box-sizing: border-box;
        text-align: center;
      }
      /* 标签标题列表 */
      .tab-title {
        height: 50px;
        margin: 0 auto;
        display: flex;
      }
      .tab-title li {
        list-style: none;
        height: 50px;
        line-height: 50px;
        flex: 1; /*文字垂直居中*/
      }
      .tab-title .active {
        background-color: lightseagreen;
        color: #fff;
        font-size: 20px;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
      }
      /* 内容区域 */
      .tab-content {
        width: 100%;
        height: 150px;
        margin: 0 auto;
        border: 1px lightseagreen solid;
      }
      /* 内容默认不显示 */
      .item {
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="tab">
      <ul class="tab-title">
        <li class="active">标签1</li>
        <li>标签2</li>
        <li>标签3</li>
      </ul>
      <div class="tab-content">
        <div class="item">内容1</div>
        <div class="item">内容2</div>
        <div class="item">内容3</div>
      </div>
    </div>
    <script>
      let tabTitle = document.querySelector('.tab-title')
      let lis = tabTitle.querySelectorAll('li')
      let items = document.querySelectorAll('.item')
      window.onload = function () {
        // 默认显示第一项内容
        items[0].style.display = 'block'
      }
      for (let i = 0; i < lis.length; i++) {
        // 标题添加自定义属性data-index
        lis[i].setAttribute('data-index', i)
        lis[i].onmouseover = function () {
          // 鼠标指针悬停，所有标题取消高亮
          for (let i = 0; i < lis.length; i++) {
            lis[i].className = ''
          }
          // 当前标题高亮显示
          this.className = 'active'
          // 当前标题下标，对应着内容下标
          let dataIndex = this.getAttribute('data-index')
          // 所有内容隐藏
          for (let i = 0; i < items.length; i++) {
            items[i].style.display = 'none'
          }
          // 显示当前标题对应的内容
          items[dataIndex].style.display = 'block'
        }
      }
    </script>
  </body>
</html>
